package edu.jxnu.zhangjinsong.unemploymenttracker.controller;

import edu.jxnu.zhangjinsong.unemploymenttracker.common.Response;
import edu.jxnu.zhangjinsong.unemploymenttracker.entity.Job;
import edu.jxnu.zhangjinsong.unemploymenttracker.service.JobService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/jobs")
@CrossOrigin(origins = "*")
public class JobController {

    @Autowired
    private JobService jobService;

    /**
     * 获取岗位列表
     */
    @GetMapping
    public Response getAllJobs() {
        try {
            List<Job> jobs = jobService.getAllJobs();
            return Response.success(jobs);
        } catch (Exception e) {
            return Response.error(500, e.getMessage());
        }
    }

    /**
     * 根据ID获取岗位详情
     */
    @GetMapping("/{id}")
    public Response getJobById(@PathVariable String id) {
        try {
            Job job = jobService.getJobById(id);
            if (job == null) {
                throw new RuntimeException("Job not found with id: " + id);
            }
            return Response.success(job);
        } catch (Exception e) {
            return Response.error(404, e.getMessage());
        }
    }

    /**
     * 创建岗位
     */
    @PostMapping
    public Response createJob(@RequestBody Job job) {
        try {
            boolean success = jobService.saveJob(job);
            if (success) {
                return Response.success(job);
            } else {
                return Response.error(500, "创建岗位失败");
            }
        } catch (Exception e) {
            return Response.error(500, e.getMessage());
        }
    }

    /**
     * 更新岗位信息
     */
    @PutMapping("/{id}")
    public Response updateJob(@PathVariable String id, @RequestBody Job jobDetails) {
        try {
            boolean success = jobService.updateJob(id, jobDetails);
            if (success) {
                return Response.success(jobDetails);
            } else {
                return Response.error(404, "更新岗位失败，岗位不存在");
            }
        } catch (Exception e) {
            return Response.error(404, e.getMessage());
        }
    }

    /**
     * 删除岗位
     */
    @DeleteMapping("/{id}")
    public Response deleteJob(@PathVariable String id) {
        try {
            boolean success = jobService.deleteJob(id);
            if (success) {
                return Response.success();
            } else {
                return Response.error(404, "删除岗位失败，岗位不存在");
            }
        } catch (Exception e) {
            return Response.error(404, e.getMessage());
        }
    }
}